import { IsNull } from '../TYLibrary/Common/GlobalExtend';
import {
    T_AD,
    T_FAQ,
    T_MINI_PROGRAM,
    T_ShareInfo,
    T_USER,
    WXLoginInfo,
    T_MESSAGE,
    Logger,
    LogLevel
} from './EntityBase';

console.log("entservices...");

export var ConvertToBoolean = (b: string | number): boolean => {
    if (b == "true" || b == 1)
        return true;
    else
        return false;
}

// export var WX_request = (url: string, data?: any, method: string = "GET"): Promise<any> => {
//     return new Promise<any>(async (resolve, reject) => {
//         try {
//             wx.request({
//                 url: url,
//                 data: data,
//                 method: method,
//                 header: {
//                     'content-type': 'application/json'
//                 },
//                 success: (res) => {
//                     if (res.statusCode == 200) {
//                         let d: any = res.data;
//                         if (!IsNull(d.Msg)) {
//                             if (d.Msg == "OK")
//                                 resolve(d.Data);
//                             else
//                                 reject(d.ErrorMessage);
//                         }
//                         else
//                             resolve(res.data);
//                     }
//                     else
//                         reject("获取服务器数据错误！");
//                 },
//                 fail: (res) => {
//                     reject("获取服务器数据错误！");
//                 }
//             });
//         }
//         catch (e) {
//             reject(e);
//         }
//     });
// };

export var WX_request = (url: string, data?: any, method: string = "GET"): Promise<any> => {
    return new Promise<any>(async (resolve, reject) => {
        try {
            wx.request({
                url: url,
                data: data,
                method: method,
                header: {
                    "content-type": "application/x-www-form-urlencoded",
                    EncryptStr: wx.getStorageSync("EncryptStr") || "",
                    UnionId: wx.getStorageSync("UnionId") || ""
                },
                success: async res => {
                    if (res.statusCode == 200) {
                        let d: any = res.data;
                        if (!IsNull(d.CODE)) {
                            if (d.CODE == 200)
                                resolve(d.RESULT);
                            else
                                reject(d.MSG);
                        }
                        else
                            resolve(res.data);
                    }
                    else
                        reject("获取服务器数据错误！" + res.statusCode);
                },
                fail: res => {
                    //reject("获取服务器数据错误！" + res.statusCode);
                    reject(res.errMsg);
                }
            });
        }
        catch (e) {
            reject(e);
            //console.log(e, WX_request);
        }
    });
};

export var WX_login = (errorCount: number = 0): Promise<string> => {
    return new Promise<string>(async (resolve, reject) => {
        try {
            wx.login({
                success: (res) => {
                    resolve(res.code);
                },
                fail: async (res) => {
                    errorCount++;
                    if (errorCount == 3)
                        reject("登录失败！");
                    else
                        resolve(await WX_login(errorCount));
                }
            });
        }
        catch (e) {
            reject(e);
        }
    });
};

export var WX_getUserInfo = (errorCount: number = 0): Promise<{ userInfo: any, encryptedData: string, iv: string }> => {
    return new Promise<{ userInfo: any, encryptedData: string, iv: string }>(async (resolve, reject) => {
        try {
            wx.getUserInfo({
                success: (res) => {
                    //一定要把加密串转成URI编码
                    //let encryptedData = encodeURIComponent(res.encryptedData);
                    //let iv = res.iv;
                    resolve({ userInfo: res.userInfo, encryptedData: res.encryptedData, iv: res.iv });
                },
                fail: async (res) => {
                    errorCount++;
                    if (errorCount == 3)
                        reject("获取用户信息失败！");
                    else
                        resolve(await WX_getUserInfo(errorCount));
                }
            });
        }
        catch (e) {
            reject(e);
            //console.log(e, 'WX_getUserInfo');
        }
    });
};

export var TYLogins = (loginUrl: string): Promise<WXLoginInfo> => {
    return new Promise<WXLoginInfo>(async (resolve, reject) => {
        try {
            wx.showLoading({
                title: "登陆中..."
            });
            //wx.setNavigationBarTitle({ title: "登录中..." });
            let code = await WX_login();
            let u = await WX_getUserInfo();
            let r = await WX_request(
                loginUrl,
                {
                    code: code,
                    encryptedData: u.encryptedData,
                    iv: u.iv
                }, "POST");
            let result = new WXLoginInfo();
            result.Name = u.userInfo.nickName;
            result.PICUrl = u.userInfo.avatarUrl;
            result.OpenID = r.USERINFO.OPENID;
            result.UnionID = r.USERINFO.UNIONID;
            if (IsNull(result.UnionID) || result.UnionID == '') {
                result.UnionID = result.OpenID;
            }
            wx.setStorageSync("EncryptStr", r.ENCRYPTSTR);
            wx.setStorageSync("UnionId", result.UnionID);
            resolve(result);
        }
        catch (e) {
            reject(e);
            Logger.Error(LogLevel.L1, "TYLogin", e);
        }
        finally {
            wx.hideLoading();
        }
    });
}
export var UserLogin = (UserLoginUrl: string, UserName: string, AvatarUrl: string, UnionId: string, OpenId: string, ReferralCode?: string, encryptedData?: string, iv?: string): Promise<T_USER> => {
    return new Promise<T_USER>(async (resolve, reject) => {
        try {
            let r;
            if (ReferralCode && encryptedData && iv)
                r = await WX_request(UserLoginUrl, { UserName, AvatarUrl, UnionId, OpenId, ReferralCode, encryptedData, iv });
            else if (ReferralCode)
                r = await WX_request(UserLoginUrl, { UserName, AvatarUrl, UnionId, OpenId, ReferralCode });
            else
                r = await WX_request(UserLoginUrl, { UserName, AvatarUrl, UnionId, OpenId });
            resolve(r);
        }
        catch (e) {
            reject(e);
        }
    });
};

export var QueryAllAD = (QueryAdUrl: string): Promise<Array<T_AD>> => {
    return new Promise<Array<T_AD>>(async (resolve, reject) => {
        try {
            let r = await WX_request(QueryAdUrl);
            resolve(r);
        }
        catch (e) {
            reject(e);
        }
    });
};
//查询常见问题
export var QueryAllFAQ = (QueryAllFAQUrl: string): Promise<Array<T_FAQ>> => {
    return new Promise<Array<T_FAQ>>(async (resolve, reject) => {
        try {
            resolve(await WX_request(QueryAllFAQUrl));
        }
        catch (e) {
            reject(e);
        }
    });
}
//查询推荐小程序
export var QueryMiniProgram = (QueryMiniProgramUrl: string): Promise<Array<T_MINI_PROGRAM>> => {
    return new Promise<Array<T_MINI_PROGRAM>>(async (resolve, reject) => {
        try {
            resolve(await WX_request(QueryMiniProgramUrl));
        }
        catch (e) {
            reject(e);
        }
    });
}
//查询推荐小程序数量
export var QueryMiniProgramCount = (QueryMiniProgramCountUrl: string): Promise<number> => {
    return new Promise<number>(async (resolve, reject) => {
        try {
            resolve(await WX_request(QueryMiniProgramCountUrl));
        }
        catch (e) {
            reject(e);
        }
    });
}
export var QueryIsAgree = (QueryIsAgreeUrl: string, OpenId: string): Promise<boolean> => {
    return new Promise<boolean>(async (resolve, reject) => {
        try {
            resolve(await WX_request(QueryIsAgreeUrl, { OpenId }));
        }
        catch (e) {
            reject(e);
        }
    });
}
//查询全部消息
export var QueryAllMessage = (QueryAllMessageUrl: string, UnionId: string): Promise<Array<T_MESSAGE>> => {
    return new Promise<Array<T_MESSAGE>>(async (resolve, reject) => {
        try {
            let l = new Array<T_MESSAGE>();
            let r = await WX_request(QueryAllMessageUrl, { UnionId: UnionId });
            if (r && r.length) {
                r.forEach(el => {
                    let i = new T_MESSAGE();
                    i.CREATETIME = (el.CREATETIME as String)
                        .ToDate()
                        .Format("yyyy-MM-dd");
                    i.ID = el.ID;
                    i.CONTENT = el.CONTENT;
                    i.ISREAD = el.ISREAD;
                    i.TYPE = el.TYPE;
                    i.UNIONID = el.UNIONID;
                    l.push(i);
                });
            }
            resolve(l);
        } catch (e) {
            reject(e);
        }
    });
};
//查询未读消息数量
export var QueryNoReadMessageCount = (QueryNoReadMessageCountUrl: string, UnionId: string): Promise<number> => {
    return new Promise<number>(async (resolve, reject) => {
        try {
            let c = await WX_request(QueryNoReadMessageCountUrl, { UnionId: UnionId });
            resolve(c);
        } catch (e) {
            reject(e);
        }
    });
};

export var GetOpenId = (GetOpenIdUrl: string): Promise<string> => {
    return new Promise<string>(async (resolve, reject) => {
        try {
            let code = await WX_login();
            let r = await WX_request(GetOpenIdUrl, { code });
            resolve(r);
        }
        catch (e) {
            reject(e);
        }
    });
};
export var GetShareInfo = (GetShareInfoUrl: string): Promise<Array<T_ShareInfo>> => {
    return new Promise<Array<T_ShareInfo>>(async (resolve, reject) => {
        try {
            let r = await WX_request(GetShareInfoUrl);
            resolve(r);
        }
        catch (e) {
            reject(e);
        }
    });
};

export var AddTRecommend = (AddTRecommendUrl: string, ReferralCode: string, UnionId: string): Promise<void> => {
    return new Promise<void>(async (resolve, reject) => {
        try {
            let r = await WX_request(AddTRecommendUrl, { ReferralCode, UnionId });
            resolve(r);
        }
        catch (e) {
            reject(e);
        }
    });
};

//免责同意
export var AgreeAgreement = (AgreeAgreementUrl: string, OpenId: string): Promise<boolean> => {
    return new Promise<boolean>(async (resolve, reject) => {
        try {
            let r = await WX_request(AgreeAgreementUrl, { OpenId: OpenId });
            resolve(r);
        } catch (e) {
            reject(e);
        }
    });
};

//领取VIP
export var ReceiveVip = (ReceiveVipUrl: string, UnionId: string): Promise<T_USER> => {
    return new Promise<T_USER>(async (resolve, reject) => {
        try {
            let r = await WX_request(ReceiveVipUrl, { UnionId });
            resolve(r);
        } catch (e) {
            reject(e);
        }
    });
};